package com.alpha.servlets;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpha.dao.CategoryDao;

/**
 * Servlet implementation class AddCategoryServlet
 */
@WebServlet("/AddCategoryServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class AddCategoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(AddCategoryServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCategoryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		logger.info(this.getClass().getSimpleName()+" post method started.");
		
		String categoryName = "";
		
		if(request.getParameter("category_name")!=null){
			categoryName = request.getParameter("category_name");
		} else {
			response.sendRedirect("CategoriesAdmin.jsp?error=Invalid+action!");
			return;
		}
		
		CategoryDao cDao = new CategoryDao();
		try {
			cDao.insertCategory(categoryName);
			ServletContext application = this.getServletContext();
			application.setAttribute("categories", cDao.retrieveAllCategories());
			response.sendRedirect("CategoriesAdmin.jsp?success=Successfully+added+category!");
			return;
		} catch (Exception e) {
			logger.error(e.getMessage());
			response.sendRedirect("CategoriesAdmin.jsp?error=Cannot+add+category.");
			return;
		}
		
	}

}
